package com.syl.servlet;

import com.google.gson.Gson;
import com.syl.entity.User;
import com.syl.service.UserService;
import com.syl.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname UserListServlet
 * @Description
 * @Date 2025/8/2 14:09
 * @Created by SYL
 */

@WebServlet("/userlist")
public class UserListServlet extends HttpServlet {

     UserService userService  =new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //前端ajxs没有传来数据 只要求 获取数据

        List<User> list = userService.getAllUser();
        PrintWriter writer = resp.getWriter();

        // 构造符合前端期望的响应格式
        Map<String, Object> result = new HashMap<>();
        result.put("total", list.size());
        result.put("users", list);
        System.out.println("result = " + result);

        // 使用 Gson 将对象转换为 JSON 字符串
        Gson gson = new Gson();
        String json = gson.toJson(result);
        System.out.println("json = " + json);
        // 写入响应
        resp.getWriter().write(json);

    }
}
